package xyz.keyon.servlet;

import xyz.keyon.service.IUserService;
import xyz.keyon.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "RegisterServlet", urlPatterns = "/RegisterServlet")
public class RegisterServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取响应头信息
        String name = request.getParameter("uname");
        String password = request.getParameter("upwd");
        //调用业务逻辑层
        IUserService service = new UserServiceImpl();
        int flag = service.register(name, password);
        //处理返回结果
        if(flag == 1){
            System.out.println("注册成功");
            System.out.println("username:" + name);
            System.out.println("password:" + password);
            //页面跳转（重定向）
            response.sendRedirect("QueryAllStudentsByPageServlet");
        } else if(flag == -1){
            System.out.println("该用户名已存在");
            //页面跳转（请求转发）
            request.setAttribute("status","isExist");
            request.getRequestDispatcher("register.jsp").forward(request,response);
        } else{
            System.out.println("注册失败");
            //页面跳转（请求转发）
            request.setAttribute("status","error");
            request.getRequestDispatcher("register.jsp").forward(request,response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
